package cn.com.inossem.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.inossem.adapter.YaoQingUserAdapter;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.fragment.PersonalCenterFragment;
import cn.com.inossem.model.PhoneBook;
import cn.com.inossem.model.PhoneBookList;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.PingYinUtil;
import cn.com.inossem.utils.TongxuluPinyinComparator;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;
import com.google.gson.Gson;

public class FriendList extends RequestActivity {
	YaoQingUserAdapter user_adapter = null;
	public EditText text_phone = null;
	ListView list_view = null;
	private ListView listview;
	private ArrayList<String> webNameArr;
	List<Boolean> stateList = new ArrayList<Boolean>();
	int touchState;

	ImageView sousuo, back;

	TextView addfriend, yaoqing;
	EditText editText2;
	List<PhoneBook> saveList = new ArrayList<PhoneBook>();
	private ArrayList<String> saveNameArr = new ArrayList<String>();

	List<PhoneBook> u_list = new ArrayList<PhoneBook>();

	List<PhoneBook> Xuanzhongmessage;

	private String py[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
			"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
			"X", "Y", "Z" };

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		initView();
		launchRequest(WooRequestFactory.getTongxunlu());
	}

	/**
	 * 获取联系人
	 * */
	public void testGetContacts() {
		Uri uri = Uri.parse("content://com.android.contacts/contacts"); // 访问所有联系人
		ContentResolver resolver = this.getContentResolver();
		Cursor cursor = resolver.query(uri, new String[] { "_id" }, null, null,
				null);
		StringBuilder sb = new StringBuilder();

		List<PhoneBook> list = new ArrayList<PhoneBook>();

		while (cursor.moveToNext()) {
			int contactsId = cursor.getInt(0);
			uri = Uri.parse("content://com.android.contacts/contacts/"
					+ contactsId + "/data"); // 某个联系人下面的所有数据
			Cursor dataCursor = resolver.query(uri, new String[] { "mimetype",
					"data1", "data2" }, null, null, null);
			PhoneBook pb = new PhoneBook();
			while (dataCursor.moveToNext()) {
				String data = dataCursor.getString(dataCursor
						.getColumnIndex("data1"));
				String type = dataCursor.getString(dataCursor
						.getColumnIndex("mimetype"));
				if ("vnd.android.cursor.item/name".equals(type)) { // 如果他的mimetype类型是name
					sb.append(", name=" + data);
					pb.setFriendTruename(data);
				} else if ("vnd.android.cursor.item/phone_v2".equals(type)) { // 如果他的mimetype类型是phone
					sb.append(", \"phone\"=\"" + data + "\"");
					pb.setFriendPhone(data);
				}

			}
			list.add(pb);
		}
		Gson gson = new Gson();
		PhoneBookList pbl = new PhoneBookList();
		pbl.setListPhoneBook(list);
		String tojson = gson.toJson(pbl).toString();

		// System.out.println("通讯录：" + tojson);
		launchRequest(WooRequestFactory.tongxunlu(tojson));
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.yaoqing:
			testGetContacts();
			break;
		case R.id.addfriend:
			/*if (Xuanzhongmessage.size() > 0) {
				String str = Xuanzhongmessage.get(0).getFriendPhone();
				for (int i = 1; i < Xuanzhongmessage.size(); i++) {
					str += "," + Xuanzhongmessage.get(i);
				}
				launchRequest(WooRequestFactory.yaoqingfriends(str));
			} else {
				Toast.makeText(this, "请选择邀请的好友", Toast.LENGTH_LONG).show();
			}*/
			testGetContacts();
			break;
		case R.id.back:
			finish();
			break;
		}
	}

	public static boolean isHave(String strs, String s) {
		for (int i = 0; i < strs.length() - 1; i++) {
			for (int j = i + 1; j < strs.length(); j++) {
				if (s.toLowerCase()
						.contains(strs.toLowerCase().substring(i, j))) {
					return true;
				}
			}
		}
		return false;

	}

	private void initView() {
		Xuanzhongmessage = new ArrayList<PhoneBook>();

		sousuo = (ImageView) this.findViewById(R.id.sousuo);
		sousuo.setOnClickListener(this);
		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);

		yaoqing = (TextView) this.findViewById(R.id.yaoqing);
		yaoqing.setOnClickListener(this);
		addfriend = (TextView) this.findViewById(R.id.addfriend);
		addfriend.setOnClickListener(this);
		editText2 = (EditText) this.findViewById(R.id.editText2);
		editText2.addTextChangedListener(textWatcher);
		list_view = (ListView) findViewById(R.id.listView1);

		listview = (ListView) findViewById(R.id.listview);

		listview.setAdapter(new ListAdapter() {

			@Override
			public void unregisterDataSetObserver(DataSetObserver observer) {
				// TODO Auto-generated method stub

			}

			@Override
			public void registerDataSetObserver(DataSetObserver observer) {
				// TODO Auto-generated method stub

			}

			@Override
			public boolean isEmpty() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean hasStableIds() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public int getViewTypeCount() {
				// TODO Auto-generated method stub
				return 1;
			}

			private LayoutInflater inflater;

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				inflater = LayoutInflater.from(FriendList.this);
				convertView = inflater.inflate(R.layout.letter_layout, null);
				TextView text = (TextView) convertView;
				text.setTextSize(Utils.dip2px(FriendList.this, 3));
				text.setHeight(listview.getHeight() / 26);
				text.setText(py[position]);
				// text.setTextColor(Color.WHITE);
				return text;
			}

			@Override
			public int getItemViewType(int position) {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return py.length;
			}

			@Override
			public boolean isEnabled(int position) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean areAllItemsEnabled() {
				// TODO Auto-generated method stub
				return false;
			}
		});
		listview.setDivider(null);
		// listview.setOnItemClickListener(this);
		listview.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				touchState = event.getAction();
				int hightLevel = listview.getHeight() / 26;
				int position = (int) (event.getY() / hightLevel);
				if (position >= 0 && position < 26) {
					String s = py[position];
					// String s = ((TextView) view).getText().toString();
					// txtOverlay.setText(s);
					// txtOverlay.setVisibility(View.VISIBLE);
					// handler.removeCallbacks(disapearThread);
					// // 提示延迟1.5s再消失
					// handler.postDelayed(disapearThread, 1500);
					int localPosition = binSearch(webNameArr, s); // 接收返回值

					if (localPosition != -1) {
						// txtOverlay.setVisibility(View.INVISIBLE); //
						// 防止点击出现的txtOverlay与滚动出现的txtOverlay冲突
						list_view.setSelection(localPosition); // 让List指向对应位置的Item
					}
				}
				return false;
			}
		});
	}

	public void removeObj() {
		if (user_adapter != null) {
			user_adapter.removeUser();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	// 将选中的py与stringArr的首字符进行匹配并返回对应字符串在数组中的位置
	public static int binSearch(ArrayList<String> string, String s) {
		for (int i = 0; i < string.size(); i++) {
			if (s.equalsIgnoreCase("" + string.get(i).charAt(0))) { // ����ִ�Сд
				return i;
			}
		}
		return -1;
	}

	@Override
	public int getContentViewId() {
		// TODO Auto-generated method stub
		return R.layout.friends_layout;
	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		if (bundle.containsKey(WooRequestFactory.BUNDLE_EXTRA_SUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_SUCCESS) == 1) {
				u_list = new ArrayList<PhoneBook>();
				List<PhoneBook> retList = bundle
						.getParcelableArrayList(WooRequestFactory.BUNDLE_EXTRA_TONGXULU);
				System.out.println("retList长度：" + retList.size());
				u_list = retList;
				System.out.println("messageInfo长度：" + u_list.size());

				TongxuluPinyinComparator comparator = new TongxuluPinyinComparator();
				if (u_list.size() > 0)
					Collections.sort(u_list, comparator);
				webNameArr = new ArrayList<String>();
				for (int i = 0; i < u_list.size(); i++) {
					String py = PingYinUtil.getPingYin(u_list.get(i)
							.getFriendTruename());
					webNameArr.add(py);
					stateList.add(false);
				}

				user_adapter = new YaoQingUserAdapter(this, u_list, webNameArr,
						Xuanzhongmessage);
				list_view.setAdapter(user_adapter);

				list_view.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						// Intent intent = new Intent(FriendList.this,
						// FriendsDetailsActivity.class);
						// intent.putExtra("type", 1);
						// intent.putExtra("phone",
						// u_list.get(arg2).getUsername());
						// startActivity(intent);
						Intent intent = new Intent(FriendList.this, FriendsDetailsActivity.class);
						intent.putExtra("type", 0);
						intent.putExtra("phone", u_list.get(arg2).getFriendPhone());
						startActivity(intent);
					}
				});
			}
		} else if (bundle
				.containsKey(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS) == 1) {
				launchRequest(WooRequestFactory.getTongxunlu());
			}
		} else if (bundle
				.containsKey(WooRequestFactory.BUNDLE_EXTRA_YAOQINGSUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_YAOQINGSUCCESS) == 1) {
				Toast.makeText(this, "邀请成功", Toast.LENGTH_LONG).show();
			}
		}

	}

	private TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			Log.d("TAG", "afterTextChanged--------------->");
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.d("TAG", "beforeTextChanged--------------->");
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			Log.d("TAG", "onTextChanged--------------->");
			String str = editText2.getText().toString();
			if (str.equals("")) {
				if (user_adapter != null) {
					user_adapter.setInfoData(u_list, webNameArr);
					user_adapter.notifyDataSetChanged();
				}
			} else {
				saveList = new ArrayList<PhoneBook>();
				saveNameArr = new ArrayList<String>();
				for (int i = 0; i < u_list.size(); i++) {
					System.out.println(u_list.get(i).toString()
							+ "--------1111---------" + str);
					if (u_list.get(i).getFriendTruename().toString()
							.contains(str)) {
						// if (isHave(u_list.get(i).username, str)) {
						saveList.add(u_list.get(i));
						saveNameArr.add(webNameArr.get(i));
					}
				}
				user_adapter.setInfoData(saveList, saveNameArr);
				user_adapter.notifyDataSetChanged();
			}
		}
	};
}